<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/10/13 14:07
 */

namespace module\ai\library\channel\chat;

use module\ai\library\channel\abstract\Chat;
use module\ai\library\OpenAI\Factory;

class XunfeiChat extends Chat
{

    protected string $baseUrl = 'https://spark-api-open.xf-yun.com/v1';

    public function __construct(protected array $config)
    {
        $config['api_key'] = sprintf("%s:%s", $config['secret_id'], $config['secret_key']);
        parent::__construct($config);
    }

    protected function chat(): \OpenAI\Resources\Chat|\module\ai\library\OpenAI\Chat
    {
        if (!$this->client) {
            $this->client = (new Factory())->withApiKey($this->apiKey)
                ->withBaseUri($this->baseUrl)
                ->make();
        }
        $chat = $this->client->chat();
        $chat->withFormatData(function ($data) {
            $data['id'] = $data['id'] ?? $data['sid'] ?? '';
            $data['object'] = $data['object'] ?? 'chat.completion';
            $data['created'] = $data['created'] ?? time();
            $data['model'] = $data['model'] ?? $this->payload['model'] ?? '';
            if (isset($data['choices'][0]['delta']) && isset($data['usage'])) {
                $data['choices'][0]['finish_reason'] = 'stop';
            }
            return $data;
        });

        return $chat;
    }
}